import { useEffect, useRef, useState } from 'react'

/**
 * 自适应父容器的高与宽
 * @constructor
 */
const AutoSizeContainer = (props: any) => {
	const divRef = useRef<HTMLDivElement>(null)
	const [width, setWidth] = useState('100%')
	const [height, setHeight] = useState('0px')
	const newProps = { ...props, style: { ...props.style, width: width, height: height, overflow: 'auto' } }
	const updateSize = () => {
		setHeight('0px')
		setHeight(divRef.current!.parentElement!.clientHeight.toString() + 'px')
	}
	const onResize = () => {
		updateSize()
	}
	useEffect(() => {
		updateSize()
		window.addEventListener('resize', onResize)
		return () => {
			window.removeEventListener('resize', onResize)
		}
	}, [])
	return (
		<div ref={divRef} {...newProps}>
			{props.children}
		</div>
	)
}

export default AutoSizeContainer
